package com.tplhk.app.callactivity.service.impl;


import com.tplhk.app.callactivity.constants.CallActivityConstants;
import com.tplhk.app.callactivity.model.param.CallActivityRequestParam;
import com.tplhk.app.callactivity.model.param.TaskLeaderSignConfirmParam;
import com.tplhk.app.callactivity.model.param.TaskCounterSignatureSubConfirmParam;
import com.tplhk.app.callactivity.model.param.TaskDraftOfficialDocumentsConfirmParam;
import com.tplhk.app.callactivity.service.IBizCallActivityProcessInfoService;
import com.tplhk.app.callactivity.wrapper.CallActivityProcessVariablesWrapper;
import com.tplhk.camunda.starter.model.param.process.ProcessVariablesQueryParam;
import com.tplhk.camunda.starter.model.param.process.TaskQueryParam;
import com.tplhk.camunda.starter.model.vo.TaskVo;
import com.tplhk.camunda.starter.model.vo.TwoTuple;
import com.tplhk.camunda.starter.servcie.CamundaCommonService;
import com.tplhk.camunda.starter.util.CamundaUtils;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * 支付流程 - 业务数据 服务实现类
 *
 * @author jqxu
 * @since 2022-05-30
 */
@Service
@Slf4j
public class BizCallActivityProcessInfoServiceImpl implements IBizCallActivityProcessInfoService {

    @Resource
    private CamundaCommonService camundaCommonService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String startCallActivityProcess(CallActivityRequestParam callActivityRequestParam) {
        String busiKey = String.valueOf(System.currentTimeMillis());
        log.info("开启会议流程，processKey：{}, businessKey：{}", CallActivityConstants.Process_CallActivity_ID, busiKey);
        ProcessInstance processInstance = this.camundaCommonService.startProcessInstance(
                CallActivityConstants.Process_CallActivity_ID,
                busiKey,
                callActivityRequestParam);
        log.info("开启会议流程，结果：id = {}, getProcessInstanceId = {}, getProcessDefinitionId = {}, getBusinessKey = {}",
                processInstance.getId(),
                processInstance.getProcessInstanceId(),
                processInstance.getProcessDefinitionId(),
                processInstance.getBusinessKey());
        return busiKey;
    }

    @Override
    public String TaskDraftOfficialDocuments(TaskDraftOfficialDocumentsConfirmParam confirmParam) {
        String taskId = camundaCommonService.getTaskId(confirmParam.getProcessInstanceId(), confirmParam.getTaskId());
        if(null == taskId){
            log.error("找不到 taskId, 参数：{}, taskId: {}", confirmParam, taskId);
            return null;
        }
        confirmParam.setTaskId(taskId);

        ProcessVariablesQueryParam processVariablesQueryParam = ProcessVariablesQueryParam.builder()
                .processInstanceId(confirmParam.getProcessInstanceId())
                .build();
        Map<String, Object> existProcessVariables = this.camundaCommonService.getRuntimeProcessVariables(processVariablesQueryParam);
        log.info("获取当前已存在流程变量，结果：{}", existProcessVariables);

        // 取流程变量
        CallActivityProcessVariablesWrapper existPaymentProcessVariablesWrapper = new CallActivityProcessVariablesWrapper(existProcessVariables);
        log.info("公文起草:getMeettingName == {} ", existPaymentProcessVariablesWrapper.getMeettingName());
        log.info("公文起草:getJoinNum == {} ", existPaymentProcessVariablesWrapper.getJoinNum());

        // 本次任务新增变量
        Map<String, Object> processVariables = CamundaUtils.convertProcessVariablesFromPair(
                CallActivityConstants.VAR_NOTICE_INFO,
                confirmParam.getNoticeInfo(),
                CallActivityConstants.VAR_DRAFT_USER_NAME,
                "xjq"
                );
        this.camundaCommonService.completeTask(confirmParam.getTaskId(), processVariables);

        return confirmParam.getTaskId();
    }

    @Override
    public String TaskCounterSignatureSub(TaskCounterSignatureSubConfirmParam confirmParam) {
        ProcessInstance processInstance = camundaCommonService.getSubProcessInstance(confirmParam.getProcessInstanceId());
        if(null == processInstance){
            log.error("流程实例找不到 {}", confirmParam.getProcessInstanceId());
            return null;
        }
        String subProcessInstanceId = processInstance.getProcessInstanceId();
        log.info("subProcessInstanceId.getId():::{}", subProcessInstanceId);

        String taskId = camundaCommonService.getTaskId(subProcessInstanceId, confirmParam.getTaskId());
        if(null == taskId){
            log.error("找不到 taskId, 参数：{}, taskId: {}", confirmParam, taskId);
            return null;
        }
        confirmParam.setTaskId(taskId);

        ProcessVariablesQueryParam processVariablesQueryParam = ProcessVariablesQueryParam.builder()
                .processInstanceId(confirmParam.getProcessInstanceId())
                .build();
        Map<String, Object> existProcessVariables = this.camundaCommonService.getRuntimeProcessVariables(processVariablesQueryParam);
        log.info("获取当前已存在流程变量，结果：{}", existProcessVariables);

        // 取流程变量：子流程可以直接取主流程的变量
        CallActivityProcessVariablesWrapper existPaymentProcessVariablesWrapper = new CallActivityProcessVariablesWrapper(existProcessVariables);
        log.info("会签:getMeettingName == {} ", existPaymentProcessVariablesWrapper.getMeettingName());
        log.info("会签:getJoinNum == {} ", existPaymentProcessVariablesWrapper.getJoinNum());
        log.info("会签:getNoticeInfo == {} ", existPaymentProcessVariablesWrapper.getNoticeInfo());
        log.info("会签:getDraftUserName == {} ", existPaymentProcessVariablesWrapper.getDraftUserName());
        // 本次任务新增变量
        Map<String, Object> processVariables = CamundaUtils.convertProcessVariablesFromPair(
                CallActivityConstants.VAR_JOIN_NUM,
                existPaymentProcessVariablesWrapper.getJoinNum() + 1,
                CallActivityConstants.VAR_USER_NAME,
                confirmParam.getUserName(),
                CallActivityConstants.VAR_COUNTER_SIGN_DATE_TIME,
                LocalDate.now()
        );

        this.camundaCommonService.completeTask(confirmParam.getTaskId(),processVariables);

        return confirmParam.getTaskId();
    }

    @Override
    public String TaskLeaderSign(TaskLeaderSignConfirmParam confirmParam) {
        String taskId = camundaCommonService.getTaskId(confirmParam.getProcessInstanceId(), confirmParam.getTaskId());
        if(null == taskId){
            log.error("找不到 taskId, 参数：{}, taskId: {}", confirmParam, taskId);
            return null;
        }
        confirmParam.setTaskId(taskId);

        ProcessVariablesQueryParam processVariablesQueryParam = ProcessVariablesQueryParam.builder()
                .processInstanceId(confirmParam.getProcessInstanceId())
                .build();
        Map<String, Object> existProcessVariables = this.camundaCommonService.getRuntimeProcessVariables(processVariablesQueryParam);
        log.info("获取当前已存在流程变量，结果：{}", existProcessVariables);

        // 取流程变量
        CallActivityProcessVariablesWrapper existPaymentProcessVariablesWrapper = new CallActivityProcessVariablesWrapper(existProcessVariables);
        log.info("领导签发:getMeettingName == {} ", existPaymentProcessVariablesWrapper.getMeettingName());
        log.info("领导签发:getJoinNum == {} ", existPaymentProcessVariablesWrapper.getJoinNum());
        log.info("领导签发:getNoticeInfo == {} ", existPaymentProcessVariablesWrapper.getNoticeInfo());
        log.info("领导签发:getDraftUserName == {} ", existPaymentProcessVariablesWrapper.getDraftUserName());
        log.info("领导签发:getUserName == {} ", existPaymentProcessVariablesWrapper.getUserName());
        log.info("领导签发:getCounterSignDateTime == {} ", existPaymentProcessVariablesWrapper.getCounterSignDateTime());

        // 本次任务新增变量
        Map<String, Integer> processVariables = CamundaUtils.convertProcessVariablesFromPair(
                CallActivityConstants.VAR_APPROVAL_RESULT,
                confirmParam.getApprovalResult()
        );
        this.camundaCommonService.completeTask(confirmParam.getTaskId(), processVariables);

        return confirmParam.getTaskId();
    }


    @Override
    public TwoTuple<List<TaskVo<Object>>, Long> queryTasks(TaskQueryParam taskQueryParam) {
//        Consumer<TaskQuery> extendTaskQuery = (x) -> {
//            // 这里设置额外的查询条件
//            x.caseDefinitionKey("kkkkkkkk");
//            x.caseDefinitionId("2eeeeee");
//        };
        TwoTuple<List<TaskVo<Object>>, Long> twoTuple = this.camundaCommonService.queryRuntimeTasks(
                taskQueryParam);
        log.info("查询待处理任务列表，结果：{}", twoTuple.getFirst());

        return twoTuple;
    }


    @Override
    public TwoTuple<List<HistoricTaskInstance>, Long> queryHistoryTasks(TaskQueryParam taskQueryParam) {
        return this.camundaCommonService.queryHistoryTasks(taskQueryParam);
    }

}
